#define _CRT_SECURE_NO_WARNINGS 1

#include "SeqList.h"

void SeqListInit(SeqList* ps)
{
	ps->a = (SLDateType*)malloc(sizeof(SLDateType) * 4);
	if (ps->a == NULL)
	{
		perror("malloc");
		exit(-1);
	}
	ps->size = 0;
	ps->capacity = 4;
}

void SeqListDestroy(SeqList* ps)
{
	free(ps->a);
	ps->a = NULL;
	ps->size = ps->capacity = 0;
}

void SeqListPrint(SeqList* ps)
{
	int i = 0;
	for (i = 0; i < ps->size; i++)
	{
		printf("%d ", *((ps->a) + i));
	}
	printf("\n");
}

void SLCheckCapacity(SeqList* ps)
{
	if (ps->size == ps->capacity)
	{
		SLDateType* tmp = (SLDateType*)realloc(ps->a, sizeof(SLDateType*) * 2 * ps->capacity);
		if (tmp == NULL)
		{
			perror("realloc");
			exit(-1);
		}
		ps->a = tmp;
		ps->capacity *= 2;
	}
}

void SeqListPushBack(SeqList* ps, SLDateType x)
{
	SLCheckCapacity(ps);

	ps->a[ps->size] = x;
	ps->size++;
}

void SeqListPushFront(SeqList* ps, SLDateType x)
{
	SLCheckCapacity(ps);

	int i = 0;
	int end = ps->size - 1;
	for (i = end; i >= 0; i--)
	{
		ps->a[i + 1] = ps->a[i];
	}
	ps->a[0] = x;
	ps->size++;
}

void SeqListPopFront(SeqList* ps)
{
	assert(ps->size >0);
	int front = 1;
	while (front < ps->size)
	{
		ps->a[front - 1] = ps->a[front];
		front++;
	}
	ps->size--;
}

void SeqListPopBack(SeqList* ps)
{
	assert(ps->size >0);
	ps->size--;
}

int SeqListFind(SeqList* ps, SLDateType x)
{
	int left = 0;
	int right = ps->size - 1;
	while (left <= right)
	{
		int mid = (left + right) / 2;
		if (x > ps->a[mid])
		{
			left = mid + 1;
		}
		else if (x < ps->a[mid])
		{
			right = mid - 1;
		}
		else
		{
			return mid+1;
		}
	}
	return -1;
}

void SeqListInsert(SeqList* ps, int pos, SLDateType x)
{
	SLCheckCapacity(ps);
	assert(pos >= 1 && pos <= ps->size);
	int end = ps->size - 1;
	while (end>=pos-1)
	{
		ps->a[end + 1] = ps->a[end];
		end--;
	}
	ps->a[end + 1] = x;
	ps->size++;
}

void SeqListErase(SeqList* ps, int pos)
{
	assert(ps->size > 0);

	int tmp = pos-1;
	while (tmp < ps->size-1)
	{
		ps->a[tmp] = ps->a[tmp+1];
		tmp++;
	}
	ps->size--;
}